package com.itheima.service.imp;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.domain.Role;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.service.RoleService;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Override
    public Map<String, Object> findById(Integer id) {
        List<Role> roleList = roleDao.findAll();
        Integer [] ids = roleDao.findrRoleIdsByUserId(id);
        Map<String, Object> map =  new HashMap<>();
        map.put("roleList",roleList);
        map.put("roleIds",ids);
        return map;
    }

    @Override
    public void add(Role role) {
        roleDao.add(role);

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //忽略字符串里的空格
        if (queryString != null && queryString != "") {
            queryString = queryString.replaceAll(" ","");
        }
        PageHelper.startPage(currentPage,pageSize);
        Page<Role> page = roleDao.findCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public void updatePermission(Integer id, Integer[] ids) {
        roleDao.delete(id);
        if (ids != null && ids.length >0) {
            for (Integer integer : ids) {
                Map<String,Integer> map = new HashMap<>();
                map.put("roleId",id);
                map.put("permissionId",integer);
                roleDao.insert(map);
            }
        }
    }
}
